#include "base/logging.h"

#include "create_message_task.h"

#include "im/common/common.h"

#include "im/adapters/user_profile_adapter.h"
#include "im/adapters/session_adapter.h"
#include "im/adapters/message_outlet_adapter.h"
#include "im/adapters/message_history_adapter.h"
#include "im/adapters/recent_contact_adapter.h"
#include "im/adapters/bang_robot_adapter.h"
#include "im/adapters/im_call_center_adapter.h"

#include "bang_shopkeeper_cache.h"
#include "call_center_cache.h"
#include "image_filter.h"

namespace imserver {

bool IsBangRobotMessage(const ImMessage & message) {
  if (MessageType(message) == MSG_TYPE_TALK) {
    BangShopKeeperCache& bsc = BangShopKeeperCache::Instance();
    int shop_count = 0;
    if (bsc.Contains(message.sender)) {
      ++shop_count;
    }
    if (bsc.Contains(message.receiver)) {
      ++shop_count;
    }
    if (shop_count == 1) {
      LOG_INFO("bang message,sender=" << message.sender 
               << " receiver=" << message.receiver);
      return true;
    }
  }
  return false;
}

bool IsCallCenterMessage(const ImMessage & message) {
  if (MessageType(message) == MSG_TYPE_TALK) {
    if (CallCenterCache::Instance().IsWaiter(message.sender)) {
      return true;
    }
    if (CallCenterCache::Instance().IsCallCenter(message.receiver)) {
      return true;
    }
  }
  return false;
}

bool IsIllegalMessage(const ImMessage & message) {
  if ((message.body.find("百度") != std::string::npos && message.body.find("baidu.com") != std::string::npos)
      || message.body.find("youqian.baidu.com") != std::string::npos
      || message.body.find("jd.com") != std::string::npos
      || message.body.find("taobao.com") != std::string::npos) {
    return true;
  }

  if (message.body.find("[img]") != std::string::npos) {
    if (!im::ImageFilter::Instance().IsLegal(message.sender)) {
      LOG_WARN("Illegal image dropped. sender=" << message.sender);
      return true;
    }
  }
  return false;
}

void CreateMessageTask::run() {
  if (IsIllegalMessage(message_)) {
    LOG_WARN("IllegalMessage dropped. sender=" << message_.sender << " receiver=" << message_.receiver);
    return;
  }
  if (IsCallCenterMessage(message_)) {
    LOG_INFO("CallCenterMessage sender=" << message_.sender << " receiver=" << message_.receiver);
    ImCallCenterAdapter::Instance().DispatchMessage(message_, 2);
    return;
  }

  if (IsBangRobotMessage(message_)) {
    BangRobotAdapter::Instance().DispatchMessage(message_, 2);
    return;
  }

//ProxyRobotCache& prc = ProxyRobotCache::Instance();
//if (psc.Contains(message_.receiver) || psc.Contains(message_.sender)) {
//  return;
//}
  DispatchDefaultMessage(message_);
}

}


